***********************************************
***** DEFINE PROGRAM FOR PLACEBO GRAPHS *******
***********************************************

program rdplacebo, eclass

syntax varlist(min=1 max=1), height(integer) sample(string) [name(string) title(string) ]

token `varlist'
local outcome `1'

matrix define R_`outcome'_base = J(201,2,.)
local k = 1
while `k' <= 201{
	di "Running placebos: draw `k'"

	if `k' == 1{
		local rvar = 0
	}
	else if `k' != 1 & `k' <= 101 {
		local rvar = runiform(0,100)
	} 
	else {
		local rvar = runiform(-100,0)
	}
		
	*RD estilocales using controlling for municipality & year fixed-effects
	cap qui rdrobust `outcome' margin_mayor_left if `sample'==1, c(`rvar') vce(cluster mun_code) all
	
	if(_rc==0 & e(N_h_l)>20 & e(N_h_r)>20){
		matrix R_`outcome'_base[`k', 1] = `rvar'
		matrix R_`outcome'_base[`k', 2] = e(tau_bc) / e(se_tau_rb)
		local k = `k' + 1
	}
	else{
		di "Repeat this k (not enough observations to run rdrobust) = `k'"
	}
}
	
di "Plotting placebos t-stats outcome: `outcome' (`sample' sample)"
preserve
clear
svmat R_`outcome'_base
set scheme plotplainblind
qui su R_`outcome'_base2 if R_`outcome'_base1 == 0, d
local true `r(mean)'
drop if R_`outcome'_base1 == 0
hist R_`outcome'_base2, bcolor(gs10)  percent addplot(pci `height' `true' 0 `true', ///
lwidth(medthick) lcolor(cranberry) lpattern(dash)) legend(off) xtitle("t-stats from placebo thresholds") name(`name') title(`title', ring(0) pos(10) margin(medlarge) size(med))
/*graph export "${root}/paper/figures/placebo_tstats_`name'.pdf", replace*/
restore
	
di "Calculating freq t-stats > true-t: `outcome'"
preserve
clear
svmat R_`outcome'_base
qui su R_`outcome'_base2 if R_`outcome'_base1 == 0, d
gen true_t = `r(mean)'
gen higher = 0
replace higher = 1 if abs(R_`outcome'_base2) > abs(true_t)
drop if R_`outcome'_base1 == 0
sum higher
di "Freq t-stats > true-t = `r(mean)'"
restore

end
